<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015-07-29
 * Time: 9:33
 */
class mobileapi_rpc_orderaddingtimer extends mobileapi_frontpage {
    function __construct($app){
        parent::__construct($app);
        $this->secret = '64f420a7-432b-4d17-824b-ceb3a686a3ec';
        $this->appkey = '249d3566-f51f-43c4-aa0f-6ddf32e8fb4e';
        $this->format = 'json';
        $this->v = '1.0';
        $this->token = 'c4cad18f-2e8f-467d-b4ec-da511b6949e9';
        $this->url = "http://120.26.115.70:6060/wtdex-service/ws/openapi/rest/route";
    }

//添加订单到海外平台
    function ordersadd (){
        //        查询所有订单表的新数据
        $sql = "select o.*,g.goods_id,g.tip_id,oi.order_id,oi.bn,oi.name,oi.nums,oi.price,oi.amount from sdb_b2c_orders as o
left join sdb_b2c_order_items as oi on o.order_id = oi.order_id
left join sdb_b2c_goods as g on oi.goods_id = g.goods_id
where o.ship_status = '0' and o.pay_status= '1' and o.status='active' and o.is_send_customs = '0' and (g.tip_id = '3' or g.tip_id = '4') and (o.cardnum is NOT NULL or o.cardnum != '') group by o.order_id";
        $arr1 = kernel::database()->select($sql);

//        查询订单商品表，每个订单号内的商品信息
        $arr2 = $arr1;
//        $sql = "select i.order_id,i.product_id,i.name,i.nums,i.price,i.amount from ".kernel::database()->prefix."b2c_order_items as i
//                left join ".kernel::database()->prefix."b2c_orders as o on i.order_id = o.order_id";
//        $arr2 = kernel::database()->select($sql);

//        遍历订单商品数组，返回以订单号为下标的二维数组
        $num = count($arr2);
        foreach ($arr2 as $k => $value) {
//            先判断该下标的元素是否存在，存在则以该元素的订单号为下标组成一个新的数组，否则跳过该次循环
            if(!empty($arr2[$k])){
                $data[$value['order_id']][] = $value;
//                再遍历订单商品表
                for($i = $k+1;$i < count($arr2);$i++){
//                    先判断外循环的元素是否存在
                    if(!empty($arr2[$i])){
//                        接着判断外循环元素的订单号与内循环元素的订单号是否一致
                        if($value['order_id']==$arr2[$i]['order_id']){
//                            一致则添加进新的数组，组合成接口参数
                            $data[$value['order_id']][] = $arr2[$i];
//                            删除比较过的订单商品数组的元素
                            unset($arr2[$k],$arr2[$i]);
                        }
                    }
                }
            }else{
                continue;
            }
        }
        $param =array();
//        嵌套循环订单数组和订单商品数组
        $j = 0;
        foreach ($arr1 as $k => $value) {
            foreach ($data as $oid => $goods) {
                if($value['order_id'] == $oid){
                    //          将订单表的ship_area字段值拆分成省，市，区
                    $ship_area = explode(':',str_replace('mainland:','',$arr1[$k]['ship_area']));
                    $ship_area = explode('/',$ship_area[0]);


                    $goods_total_price = 0;
                    $orderItemList = array();
                    //   组合orderItemList参数
                    foreach ($goods as $key => $val) {
                        $orderItemList['orderItems'][$key]['productId'] = $val['bn'];//商品编码
                        $orderItemList['orderItems'][$key]['productName'] = $val['name'];//商品名称
                        $orderItemList['orderItems'][$key]['qty'] = $val['nums'];//商品数量
                        $orderItemList['orderItems'][$key]['price'] = $val['price'];//商品单价
                        $orderItemList['orderItems'][$key]['total'] = $val['amount'];//付款金额

                        $goods_total_price += $val['amount'];
                    }

                    $param['orders'][$j] = array(
                        'orderId' => $value['order_id'],//订单号
                        'orderDate' => date("Y-m-d H:i:s",$value['createtime']),//订单日期
                        'name' => $value['ship_name'],//顾客姓名
                        'province' => $ship_area[0],//送货省
                        'city' => $ship_area[1],//送货市
                        'area' => $ship_area[2],//送货区/县
                        'addr' => $value['ship_addr'],//送货地址
                        'cardType' => '0',//证件类型
                        'cardNo' => $value['cardnum'],//顾客身份证
                        'phone' => $value['ship_mobile'],//联系电话1
                        'total' => $goods_total_price,//订单总金额(待确定)
                        'freight' => $value['cost_freight'],//运费
                        'insuredFee' => $value['cost_protect'],//保价费用
                        'portCode' => '5141',//口岸编码
                        'busiMode' => 'BC',//所属业务模式
                        'whCode' => 'HKFL',//发货仓库代号
                        'pickMode' => 0,
                        'expressCode' => 'SF',//物流公司编码
                        'orderItemList' => $orderItemList,
                    );

                    $j = $j+1;
                }
            }
        }
//      实例数据
       /* $param['orders'][0] = array(
            'orderId' => '150818001594940',//订单号
            'orderDate' => '2015-08-18 00:15:12',//订单日期
            'name' => '周锐',//顾客姓名
            'province' => '广东',//送货省
            'city' => '广州市',//送货市
            'area' => '天河区',//送货区/县
            'addr' => '广东广州市天河区珠江东路30号广州银行大厦18楼',//送货地址
            'cardType' => '0',//证件类型
            'cardNo' => '510122199209133379',//顾客身份证
            'phone' => '13512704451',//联系电话1
            'total' => '39',//订单总金额(待确定)
            'freight' => '30.00',//运费
            'insuredFee' => '0.00',//保价费用
            'portCode' => '5141',//口岸编码
            'busiMode' => 'BC',//所属业务模式
            'whCode' => 'HKFL',//发货仓库代号
            'pickMode' => 0,
            'expressCode' => 'YT',//物流公司编码
            'orderItemList' => array(
                'orderItems' => array(
                    0 => array(
                        'productId' => '4901872818310',
                        'productName' => '资生堂洗颜专科　Perfect洗面奶120g',
                        'qty' => '1',
                        'price' => '39.00',
                        'total' => '39.00',
                    ),
                ),
            ),
        );*/

        $method = 'wtdex.trade.order.batch';
        $secret = $this->secret;
        $appkey = $this->appkey;
        $format = $this->format;
        $parm = json_encode($param);
        $time = date("Y-m-d H:i:s",time());
        $v = $this->v;
        $token = $this->token;

        $sign = "{$secret}{$appkey}{$format}{$method}{$parm}{$time}{$token}{$v}{$secret}";
        $sign = base64_encode(strtolower(md5($sign)));
//        生成url，post参数
        $url = $this->url;
        $post_arr = array(
            'appkey' => $appkey,
            'sign' => $sign,
            'token' => $token,
            'v' => $v,
            'format' => $format,
            'method' => $method,
            'timestamp' => $time,
            'params' => $parm,
        );
//        用curl函数模拟post请求，最后关闭curl对象
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post_arr);
        $res = curl_exec($curl);
        curl_close($curl);
        $res = json_decode($res);
/*//      获取海外接口返回的code值
        $state = $res->response->code;
//      判断该值,若为1,则是操作成功(目前测试阶段所以为0,0是操作失败)
        if($state == 1){
//            遍历订单主表数组,组合订单号数组,然后在分割成字符串
            foreach ($arr1 as $val){
                $vals[] = $val['order_id'];
            }
            $str = implode(',',$vals);
//            然后将发送过去的这些订单ship_status状态由0(未发货)改为2(部分发货/已发送海外平台),
            $sql = "update ".kernel::database()->prefix."b2c_orders set ship_status = '2' where order_id in $str ";
        }*/
        return $res;

    }

}